package learn_concurrent._5;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// 同步模式 保护性暂停
public class T1 {
	static final Logger logger = LoggerFactory.getLogger(T1.class);

	public static void main(String[] args) {
		
		GuardedObject guardedObject = new GuardedObject();
		
		new Thread(() -> {
			logger.info("get value....");
			Object value = guardedObject.get(1000);
			logger.info("value = {}", value);
		}, "t1").start();
		
		new Thread(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			logger.info("complete value...");
			guardedObject.complete(Integer.valueOf(1001));
		}, "t2").start();
		
	}

}

class GuardedObject {

	private Object response;

	public Object get(long timeout) {
		synchronized (this) {
			long startTime = System.currentTimeMillis();
			long passedTime = 0;
			
			while (response == null) {
				long waitTime = timeout - passedTime;
				if(waitTime <= 0) {
					break;
				}
				try {
					this.wait(waitTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				passedTime = System.currentTimeMillis() - startTime;
			}
			return response;
		}
	}

	public void complete(Object value) {
		synchronized (this) {
			response = value;
			this.notifyAll();
		}
	}
}
